<template>
  <div class="auth-page">
    <div class="container page">
      <div class="row">
        <div class="col-md-6 offset-md-3 col-xs-12">
          <h1 class="text-xs-center">Sign in</h1>
          <p class="text-xs-center">
            <router-link to="/register">Need an account?</router-link>
          </p>

          <ul class="error-messages" v-if="this.errors">
            <li v-for="(value, key, index) in this.errors" :key="index">
              {{key}} {{value[0]}}
            </li>
          </ul>

          <form>
            <fieldset class="form-group">
              <input
                class="form-control form-control-lg"
                type="text"
                placeholder="Email"
                v-model.trim="user.email"
              />
            </fieldset>
            <fieldset class="form-group">
              <input
                class="form-control form-control-lg"
                type="password"
                placeholder="Password"
                v-model.trim="user.password"
              />
            </fieldset>
            <button class="btn btn-lg btn-primary pull-xs-right" @click.prevent="goLogin">
              Sign in
            </button>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {reqLogin} from '../../api/res_login'
import {mapState} from 'vuex'
export default {
  name: "LoginPages",
  data() {
    return {
      user:{
        // email: 'admin@99.com',
        // password:'admin1133',
        email: '',
        password:'',
      },
    };
  },
  methods: {
    async goLogin(){
      const result = await reqLogin(this.user)
      // 判断有没有错误
      if(JSON.stringify(this.errors) !== '{}'){
        return
      }
      const user = result.user
      // 保存用户信息
      this.$store.dispatch("saveUser", user)
      // 获取URL中的回调地址
		  const redirectUrl = this.$route.query.redirect;
      if(redirectUrl){
    		this.$router.push(redirectUrl)
      }else{
          this.$router.replace('/')
      }
    }
  },
  computed: {
    ...mapState({
      errors: state => state.errors
    })
  },
  destroyed() {
    this.$store.dispatch('clearErrors')
  },
};
</script>
<style lang="less" scoped></style>
